import redis.asyncio as aioredis
from utils import util
import json
from dateutil.parser import parse
from fastapi import FastAPI
from core.Config import settings
import models.admin.system.Config as ConfigModel
from server.Base import BaseServer

REDIS_HOST = settings.REDIS_HOST
REDIS_PORT = settings.REDIS_PORT
REDIS_DB = settings.REDIS_DB
REDIS_EXPIRE = settings.REDIS_EXPIRE

async def redis_cache() -> aioredis.Redis:
    """
    系统缓存
    :return: cache 连接池
    """
    # 从URL方式创建redis连接池
    sys_cache_pool = aioredis.ConnectionPool.from_url(
        f"redis://{REDIS_HOST}:{REDIS_PORT}",
        db=REDIS_DB,
        encoding='utf-8',
        decode_responses=True
    )
    redis = aioredis.Redis(connection_pool=sys_cache_pool)
    return redis

async def update_config_to_redis( app: FastAPI):
    result = await BaseServer(ConfigModel.Config).all()
    for item in result:
      if item["type"] and item["type"] != "group":
        key = f"config:{item['parent_code']}:{item['code']}"
        value = item['value']
        # 如果type是select_mult，则value需要转换成数组
        if item["type"] == "select_mult"  or item["type"] == "files":
          value = json.dumps(value.split(","))
        # 如果type是int，则value需要转换成int
        if item["type"] == "int":
          value = int(value)
        # 如果type是datetime 或者 date，则value需要转换成datetime
        if item["type"] == "datetime" or item["type"] == "date":
            try:
                value = await util.convert_to_timestamp(value)
            except ValueError as e:
                value = None  # or some default value
        if value :
           await app.state.cache.set(key, value)
        